package com.fenghuajueli.module_user.activity.login;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan;
import android.view.TouchDelegate;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.ui.PrivacyWebActivity;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.utils.PrivacyConstantsUtils;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.fenghuajueli.libbasecoreui.utils.RouteUtils;
import com.fenghuajueli.lib_statistics.UmEventConstant;
import com.fenghuajueli.lib_statistics.UmEventUtils;
import com.fenghuajueli.lib_data.constants.EventBusConstants;
import com.fenghuajueli.lib_data.entity.eventbus.EventEntity;
import com.fenghuajueli.module_route.UserModuleRoute;
import com.fenghuajueli.module_user.R;
import com.fenghuajueli.module_user.activity.UserViewModelBaseActivity;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel;
import com.fenghuajueli.module_user.model.UserViewModel;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.fenghuajueli.module_user.databinding.ActivityLoginBinding;

@Route(path = UserModuleRoute.USER_LOGIN)
public class LoginActivity extends UserViewModelBaseActivity implements View.OnClickListener {
    private boolean pwdIsShow = false;

    ActivityLoginBinding binding;

    /**
     * 传递过来的需要跳转到vip页面参数的值 type的值等于这个才跳转到vip开通页面
     */
    private static final String NEED_TO_VIP = "needToVip";

    /**
     * 此参数用来判断登录成功之后是否跳转到vip购买页面
     * ，根据运营需求来传递
     */
    @Autowired(name = "type")
    String type = "";
    /**
     * 此参数只是统计事件才用到的，不是项目通用参数
     */
    @Autowired(name = RouteUtils.PARAMETER_FUN_TYPE)
    int funType = 0;
    private boolean phoneIsInputComplete = false;
    private boolean passwordIsInputComplete = false;
    private final UserViewModel userViewModel = new UserViewModel();

    /**
     * 用户是否勾选了同意用户协议等
     */
    public static final String KEY_APPLY_PRIVACY = "login_apply_privacy";


    @Override
    public BaseViewModel setBaseViewModel() {
        return userViewModel;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);
        initPrivacy();
        setTextChangeListener();
        initClick();
        binding.tvAppName.setText(AppConfigInfo.APP_NAME);
        //阿里云一键登录授权的key
        String authKey = "";
        userViewModel.initOneKeyLogin(getApplication(), authKey, false);
        userViewModel.oneKeyLoginAuthSuccess.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String accessToken) {
                if (!TextUtils.isEmpty(accessToken)) {
                    userViewModel.loginByAccessToken(LoginActivity.this, accessToken, type);
                }
            }
        });
    }

    private void initClick() {
        binding.btnLogin.setOnClickListener(this);
        binding.ivClose.setOnClickListener(this);
        binding.tvRegister.setOnClickListener(this);
        binding.tvForgetPassword.setOnClickListener(this);
        binding.tvWxLogin.setOnClickListener(this);
        binding.ivChangePwdStatus.setOnClickListener(this);
        binding.btnOneKeyLogin.setOnClickListener(this);
        binding.checkView.setOnClickListener(this);
        binding.checkView.setSelected(checkAgree());
        expendTouchArea(binding.checkView, ConvertUtils.dp2px(150));
    }

    /**
     * 初始化协议相关
     */
    private void initPrivacy() {
        String first = "已阅读并同意 ";
        String second = "《用户协议》";
        String third = "《隐私政策》";
        SpannableString spannableString = new SpannableString(first + second + third);
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#0091FF"));
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线,其实默认也是true，如果要下划线的话可以不设置
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                PrivacyWebActivity.start(LoginActivity.this, PrivacyConstantsUtils.ProtocolType.USER_PROTOCOL);
            }
        };
        spannableString.setSpan(clickableSpan, first.length(), first.length() + second.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        clickableSpan = new ClickableSpan() {
            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#0091FF"));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(@NonNull View widget) {
                PrivacyWebActivity.start(LoginActivity.this, PrivacyConstantsUtils.ProtocolType.PRIVACY);
            }
        };
        spannableString.setSpan(clickableSpan, first.length() + second.length(), spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        binding.tvPrivacy.setText(spannableString);
        binding.tvPrivacy.setHighlightColor(Color.TRANSPARENT);
        binding.tvPrivacy.setMovementMethod(LinkMovementMethod.getInstance());
    }


    private void setTextChangeListener() {
        binding.etInputPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    phoneIsInputComplete = false;
                } else {
                    phoneIsInputComplete = true;
                }
                changeButtonStatus();
            }
        });
        binding.etInputPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString().trim())) {
                    passwordIsInputComplete = false;
                } else {
                    passwordIsInputComplete = true;
                }
                changeButtonStatus();
            }
        });
    }

    private void changeButtonStatus() {
        if (passwordIsInputComplete && phoneIsInputComplete) {
            binding.btnLogin.setBackgroundResource(R.drawable.shape_btn_can_use_bg);
            binding.btnLogin.setEnabled(true);
        } else {
            binding.btnLogin.setBackgroundResource(R.drawable.shape_btn_not_use_bg);
            binding.btnLogin.setEnabled(false);
        }
    }

    @Override
    public void onClick(View view) {
        if (QuickClickUtils.isFastClick()) {
            return;
        }
        if (view.getId() == R.id.btnLogin || view.getId() == R.id.tvRegister ||
                view.getId() == R.id.tvForgetPassword || view.getId() == R.id.tvWxLogin
                || view.getId() == R.id.btnOneKeyLogin) {
            //这些按钮需要检测是否同意协议
            if (!checkAgree()) {
                showToast("请先阅读并同意相关协议");
                return;
            }
        }
        if (view.getId() == R.id.btnLogin) {
            UmEventUtils.onEvent(UmEventConstant.login_count);
            login();
        } else if (view.getId() == R.id.ivClose) {
            finish();
        } else if (view.getId() == R.id.tvRegister) {
            ARouter.getInstance().build(UserModuleRoute.USER_REGISTER).navigation();
        } else if (view.getId() == R.id.tvForgetPassword) {
            ARouter.getInstance().build(UserModuleRoute.USER_FORGET_PASSWORD).navigation();
        } else if (view.getId() == R.id.tvWxLogin) {
            wxLogin();
        } else if (view.getId() == R.id.ivChangePwdStatus) {
            if (pwdIsShow) {
                binding.etInputPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                binding.ivChangePwdStatus.setImageResource(R.mipmap.aa_icon_to_view);
            } else {
                binding.etInputPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                binding.ivChangePwdStatus.setImageResource(R.mipmap.aa_icon_close_look_at);
            }
            pwdIsShow = !pwdIsShow;
            binding.etInputPassword.postInvalidate();
        } else if (view.getId() == R.id.btnOneKeyLogin) {
            userViewModel.checkOneKeyLoginEnv();
        } else if (view.getId() == R.id.checkView) {
            saveAgreeStatus(!checkAgree());
            binding.checkView.setSelected(checkAgree());
        }
    }

    private void wxLogin() {
        if (userViewModel != null) {
            userViewModel.wxLogin(this, type);
        }
    }

    private void login() {
        if (userViewModel != null) {
            userViewModel.loginByPhone(this, type,
                    binding.etInputPhone.getText().toString().trim(),
                    binding.etInputPassword.getText().toString().trim());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(EventEntity eventBusEntity) {
        if (eventBusEntity.getCode() == EventBusConstants.REGISTER_SUCCESS) {
            if (!TextUtils.isEmpty(type) && NEED_TO_VIP.equals(type)) {
                //从评论对话框来的需要跳转至购买页面
                RouteUtils.routeToOpenVip();
            }
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (userViewModel != null) {
            userViewModel.destroyOneKeyLogin();
        }
        EventBus.getDefault().unregister(this);
    }

    public void saveAgreeStatus(boolean agree) {
        MmkvUtils.save(KEY_APPLY_PRIVACY, agree);
    }

    public boolean checkAgree() {
        return MmkvUtils.get(KEY_APPLY_PRIVACY, false);
    }

    public void expendTouchArea(final View view, final int expendSize) {
        if (view != null) {
            final View parentView = (View) view.getParent();

            parentView.post(new Runnable() {
                @Override
                public void run() {
                    Rect rect = new Rect();
                    view.getHitRect(rect); //如果太早执行本函数，会获取rect失败，因为此时UI界面尚未开始绘制，无法获得正确的坐标
                    rect.left -= expendSize;
                    rect.top -= expendSize;
                    rect.right += expendSize;
                    rect.bottom += expendSize;
                    parentView.setTouchDelegate(new TouchDelegate(rect, view));
                }
            });
        }
    }
}